<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      left-arrow
      title="文章详情"
      @click-left="$router.back()"
    />
    <!-- /导航栏 -->

    <div class="article-wrap">
      <!-- 文章标题 -->
      <h1 class="title">{{ article.title }}</h1>
      <!-- /文章标题 -->

      <!-- 用户信息 -->
      <van-cell class="user-info" center :border="false">
        <van-image
          class="avatar"
          slot="icon"
          round
          fit="cover"
          :src="article.aut_photo"
        />
        <div slot="title" class="name">{{ article.aut_name }}</div>
        <div slot="label" class="pubdate">
          {{ article.pubdate | relativeTime }}
        </div>
        <van-button
          class="follow-btn"
          :type="article.is_followed ? 'default' : 'info'"
          color="#3296fa"
          round
          @click="onFollow"
          size="small"
          :loading="isFollowLoading"
          :icon="article.is_followed ? '' : 'plus'"
          >{{ article.is_followed ? '已关注' : '关注' }}</van-button
        >
      </van-cell>
      <!-- /用户信息 -->

      <!-- 文章内容 -->
      <div
        class="markdown-body"
        v-html="article.content"
        ref="article-content"
      ></div>

      <!-- 文章评论 -->
      <comment-list
        :source="articleId"
        :list="commentList"
        @update-total-count="totalCommentCount = $event"
        @reply-click="onReplyClick"
      />
      <!-- 文章评论 -->
    </div>

    <!-- 底部区域 -->
    <div class="article-bottom">
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
        @click="isPostShow = true"
        >写评论</van-button
      >
      <van-icon name="comment-o" :info="totalCommentCount" color="#777" />
      <van-icon
        :color="article.is_collected ? 'orange' : '#777'"
        :name="article.is_collected ? 'star' : 'star-o'"
        @click="onCollect"
      />
      <van-icon
        :color="article.attitude === 1 ? 'hotpink' : '#777'"
        :name="article.attitude === 1 ? 'good-job' : 'good-job-o'"
        @click="onLike"
      />
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- /底部区域 -->

    <!-- 发布评论 -->
    <van-popup v-model="isPostShow" position="bottom">
      <post-comment :target="articleId" @post-success="onPostSuccess" />
    </van-popup>
    <!-- 发布评论 -->

    <!-- 评论回复 -->
    <van-popup v-model="isReplyShow" position="bottom" style="height: 95%">
      <comment-reply
        :comment="replyComment"
        @close="isReplyShow = false"
        v-if="isReplyShow"
      />
    </van-popup>
    <!-- /评论回复 -->
  </div>
  <!-- /加载完成-文章详情 -->
</template>

<script>
import { ImagePreview } from 'vant'
import './github-markdown.css'
import {
  getArticleById,
  addCollect,
  deleteCollect,
  addLike,
  deleteLike,
} from '@/api/article'
import { addFollow, deleteFollow } from '@/api/user'
import CommentList from './components/comment-list'
import PostComment from './components/post-comment'
import CommentReply from './components/comment-reply'

export default {
  name: 'ArticleIndex',
  components: {
    CommentList,
    PostComment,
    CommentReply,
  },
  props: {
    articleId: {
      type: [Number, String, Object],
      required: true,
    },
  },
  data() {
    return {
      replyComment: {},
      article: {}, // 文章数据对象
      isFollowLoading: false,
      isCollectLoading: false,
      isPostShow: false,
      commentList: [], // 文章评论列表
      totalCommentCount: 0, // 评论总数量
      isReplyShow: false,
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loadArticle()
  },
  mounted() {},
  methods: {
    async loadArticle() {
      const { data } = await getArticleById(this.articleId)
      this.article = data.data

      this.$nextTick(() => {
        this.handlePreviewImage()
      })
    },

    handlePreviewImage() {
      // 获取文章内容dom容器
      const articleContent = this.$refs['article-content']
      // 得到所有img
      const imgs = articleContent.querySelectorAll('img')
      const imgPaths = [] // 收集所有的图片路径
      // 循环img列表，给img 注册点击事件
      imgs.forEach((img, index) => {
        imgPaths.push(img.src)
        img.onclick = function () {
          // 事件处理函数中调用ImagePreview()浏览}
          ImagePreview({
            images: imgPaths, // 预览图片路径列表
            startPosition: index, // 起始位置
          })
        }
      })
    },

    async onFollow() {
      this.isFollowLoading = true
      // 如果已关注，则取消关注
      const authorId = this.article.aut_id
      if (this.article.is_followed) {
        await deleteFollow(authorId)
      } else {
        // 否则添加关注
        await addFollow(authorId)
      }
      this.article.is_followed = !this.article.is_followed
      this.isFollowLoading = false
    },
    // 收藏
    async onCollect() {
      this.$toast.loading({
        message: '操作中...',
        forbidClick: true, // 禁止背景点击
      })
      // 如果已收藏，则取消收藏
      if (this.article.is_collected) {
        await deleteCollect(this.articleId)
      } else {
        // 否则添加收藏
        await addCollect(this.articleId)
      }
      this.article.is_collected = !this.article.is_collected

      this.$toast.success(`${this.article.is_collected ? '' : '取消'}收藏成功`)
    },
    // 点赞
    async onLike() {
      this.$toast.loading({
        message: '操作中...',
        forbidClick: true, // 禁止背景点击
      })
      // 如果已收藏，则取消收藏
      if (this.article.attitude === 1) {
        await deleteLike(this.articleId)
        this.article.attitude = -1
      } else {
        // 否则添加收藏
        await addLike(this.articleId)
        this.article.attitude = 1
      }

      this.$toast.success(
        `${this.article.attitude === 1 ? '' : '取消'}点赞成功`
      )
    },

    onPostSuccess(comment) {
      // 评论置于列表顶部
      this.commentList.unshift(comment)
      // 关闭弹出层
      this.isPostShow = false
      // 更新评论总数
      this.totalCommentCount++
    },

    onReplyClick(comment) {
      this.replyComment = comment
      this.isReplyShow = true
    },
  },
}
</script>

<style scoped lang="less">
.article-wrap {
  position: fixed;
  left: 0;
  right: 0;
  top: 46px;
  bottom: 44px;
  overflow-y: auto;
}
.title {
  font-size: 20px;
  color: #3a3a3a;
  padding: 24px 20px 18px;
  background-color: #fff;
  margin: 0;
}
.user-info {
  .avatar {
    width: 35px;
    height: 35px;
    margin-right: 8px;
  }
  .name {
    font-size: 14px;
    color: #333333;
  }
  .pubdate {
    font-size: 11px;
    color: #b4b4b4;
  }
  .follow-btn {
    width: 85px;
    height: 29px;
  }
}
.markdown-body {
  padding: 14px;
  background-color: #fff;
}
.article-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  height: 44px;
  border-top: 1px solid #d8d8d8;
  background-color: #fff;
  .comment-btn {
    width: 141px;
    height: 23px;
    border: 1px solid #eeeeee;
    font-size: 15px;
    line-height: 23px;
    color: #a7a7a7;
  }
  .van-icon {
    font-size: 20px;
  }
}
</style>
